package com.xyzq.cgate.core.plugin.post;

import com.alibaba.fastjson.JSON;
import com.xyzq.cgate.common.constant.Constants;
import com.xyzq.cgate.common.enums.PluginDetailEnum;
import com.xyzq.cgate.common.response.ResponseEntity;
import com.xyzq.cgate.core.plugin.IPlugin;
import com.xyzq.cgate.core.plugin.IPluginChain;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.reactive.function.BodyExtractors;
import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Description:
 * @author chenchen
 * @date 2019/6/19 14:13
 */
public class ResponsePlugin implements IPlugin {

    @Override
    public Mono<Void> execute(ServerWebExchange exchange, IPluginChain chain) {
        return chain.execute(exchange)
                .then(Mono.defer(() -> {
                    ServerHttpResponse response = exchange.getResponse();
                    ClientResponse clientResponse = exchange.getAttribute(Constants.WEBCLIENT_RESPONSE);
                    if(response.getStatusCode() != HttpStatus.OK) {
                        return response.writeWith(
                                Mono.just(exchange.getResponse()
                                        .bufferFactory()
                                        .wrap(JSON.toJSONBytes(
                                                        response.getStatusCode().getReasonPhrase()))));
                    }
                    return response.writeWith(clientResponse.body(BodyExtractors.toDataBuffers()));
                }));

    }

    @Override
    public String getPluginPhase() {
        return PluginDetailEnum.RESPONSE.getPhase();
    }

    @Override
    public int getCode() {
        return PluginDetailEnum.RESPONSE.getCode();
    }

    @Override
    public String getName() {
        return PluginDetailEnum.RESPONSE.getName();
    }
}
